package cn.etg.http;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HttpServletResponse {
    private Socket socket;
    private int statusCode=200;
    private String statusReason = "OK";
    private File contentFile;
    private Map<String,String> headers=new HashMap<>();

    public HttpServletResponse(Socket socket){
        this.socket=socket;
    }

    public void response() throws IOException {
        sendStatusLine();
        sendHeaders();
        sendContent();
    }

    private void sendStatusLine() throws IOException {
        String line = "HTTP/1.1"+" "+statusCode+" "+statusReason;
        println(line);
    }
    private void sendHeaders() throws IOException {
        Set<Map.Entry<String, String>> entries = headers.entrySet();
        for(Map.Entry<String,String> entry:entries){
           String key = entry.getKey();
           String value = entry.getValue();

           println(key+": "+value);
        }
        println("");
    }
    private void sendContent() throws IOException {
        if(contentFile!=null){
            OutputStream out = socket.getOutputStream();
            FileInputStream fis = new FileInputStream(contentFile);
            byte[] bytes = new byte[1024*10];
            int len;
            while((len=fis.read(bytes))!=-1){
                out.write(bytes,0,len);
            }
        }
    }

    /**
     * 发送响应，状态行，响应头发送一行字符串代码是一致
     * @param line
     */
    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        out.write(line.getBytes(StandardCharsets.ISO_8859_1));
        out.write(13);
        out.write(10);
    }
//  setter and getter
    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public File getContentFile() {
        return contentFile;
    }

    public void setContentFile(File contentFile) {
        this.contentFile = contentFile;
        try {
            String type = Files.probeContentType(Paths.get(contentFile.getName()));
            addHeader("Content-Type",type);
            addHeader("Content-Length",contentFile.length()+"");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void addHeader(String name,String value){
        headers.put(name,value);
    }

    /*
    重定向
     */
    public void sendRedirect(String location){
        // 设置状态码
        setStatusCode(302);
        setStatusReason("Moved Temporarily");
        // 添加响应头
        addHeader("Location",location);
    }
}
